import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart' as dd;
import 'package:get/get.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/controllers/main/login/http_const.dart';
import 'package:share_fit/app/controllers/main/login/register/register_state.dart';
import 'package:share_fit/app/network/net_const.dart';
import 'package:share_fit/app/network/net_tool.dart';
import 'package:share_fit/app/routes/routes.dart';
import 'package:share_fit/app/tools/date_tool.dart';
import 'package:share_fit/app/ute/uteped_bind.dart';

class RegisterLogic extends BaseController {

  final state = RegisterState();

  void setCodeText(value) {
    state.codeText = value;
    update(['sms_code_text']);
  }

  void setNameFocus(value) {
    state.isFocusedName = value;
    update(['register_name_focus']);
  }

  void setCodeFocus(value) {
    state.isFocusedCode = value;
    update(['register_code_focus']);
  }

  void setPwdFocus(value) {
    state.isFocusedPwd = value;
    update(['register_pwd_focus']);
  }

  void setPwd2Focus(value) {
    state.isFocusedPwd2 = value;
    update(['register_pwd2_focus']);
  }

  void setObscureText(value) {
    state.obscureText = value;
    update(['register_pwd_focus','register_pwd2_focus']);
  }

  void setBottomChecked(value){
    state.isBottomSelected = value;
    update(['register_bottom_selected']);
  }

  Future<dynamic> sendVerifyCode(String userName, String verifyType) async {
    String params = '{"user_name": "$userName", "verify_type":"$verifyType"}';

    final dio = dd.Dio();
    // dio.options.contentType='application/x-www-form-urlencoded,application/json';
    dio.options.headers.addAll(NetTool.getHeadersWithLanguage());
    dio.options.contentType = ContentType.json.toString();
    dio.interceptors.add(dd.LogInterceptor(requestBody: true, responseBody: true));
    try{
      dd.Response response = await dio.post(HttpConst.sendVerifyCode, data: params,);
      return response;
    } catch (e) {
      if(e is dd.DioException && e.response!=null) {
        return e.response!;
      }
      return '';
    }
  }

  Future<dynamic> regist(String userName, String verifyCode, String password) async {
    String reqTime = DateTool.getyyyyMMddHHmmss(DateTime.now());
    String sign = HttpConst.generateMD5('$reqTime|BmqIRrpXxQaMz7O5');
    String params = '{"user_name": "$userName", "password":"$password", "sign":"$sign", "reqTime":"$reqTime", "user_type":"2"}';

    final dio = dd.Dio();
    // dio.options.contentType='application/x-www-form-urlencoded,application/json';
    dio.options.headers.addAll(NetTool.getHeaders());
    dio.interceptors.add(dd.LogInterceptor(requestBody: true, responseBody: true));
    try{
      dd.Response response = await dio.post(HttpConst.regist, data: params,);
      return response;
    } catch (e) {
      if(e is dd.DioException && e.response!=null) {
        return e.response!;
      }
      return '';
    }
  }

  Future<dynamic> tokens(String deviceId, String userName, String method, String password, String nonce, String realm, int times) async {
    String params = '{"deviceId": "$deviceId", "method": "$method", "userName": "$userName", "domainId":"default"}';
    if(times==1) {
      var HA1 = HttpConst.generateMD5('$userName:$realm:$password');
      var HA2 = HttpConst.generateMD5('str1:str2');
      var pwd = HttpConst.generateMD5('$HA1:$nonce:$HA2');
      params = '{"deviceId": "$deviceId", "method": "$method","password": "$pwd", "userName": "$userName", "nonce":"$nonce", "realm":"$realm", "str1":"str1","str2":"str2", "domainId":"default"}';
    }

    final dio = dd.Dio();
    // dio.options.contentType='application/x-www-form-urlencoded,application/json';
    dio.options.headers.addAll(NetTool.getHeaders());
    dio.interceptors.add(dd.LogInterceptor(requestBody: true, responseBody: true));
    try{
      dd.Response response = await dio.post(HttpConst.tokens, data: params,);
      Map map = jsonDecode('$response');
      if(times==0&&map['code']==401) {
        return tokens(deviceId, userName, method, password, map['data']['nonce'], map['data']['realm'], 1);
      }
      if(map['code']==200){
        String displayName = map['data']['user']['displayName'];
        save('space_person_name', displayName, global: true);
        save(NetConst.keyUserToken, map['data']['token'], global: true);
        save('expire_time_sec', map['data']['expire_time_sec'], global: true);
        save('login_state', true, global: true);
        save('login_id', map['data']['user']['id'], global: true);
      }
      return response;
    } catch(e) {
      if(e is dd.DioException && e.response!=null) {
        return e.response!;
      }
      return '';
    }
  }

  @override
  String getRemotePath() {
    return '';
  }

  @override
  void initState() {
    // TODO: implement initState
  }

  @override
  void onRemoteEvent(event, method) {
    // TODO: implement onRemoteEvent
  }

  goBack(toMainPage) {
    Future.delayed(Duration.zero, () {
      if(toMainPage) {
        Get.until((route) => Get.currentRoute== Routes.mainPage );
      } else {
        Get.offAllNamed(Routes.mainPage);
      }
    });

  }

}